import axios from "axios"
import { ElLoading, ElMessage } from "element-plus"
const DEFAULT_LOADING = true

class MYRequest {
  instance
  interceptors
  showLoading
  loading
  // 传入一些配置
  constructor(config) {
    this.instance = axios.create(config)
    this.showLoading = config.showLoading ?? DEFAULT_LOADING
    this.interceptors = config.interceptors
    // 添加当前创建实例的 => 请求拦截器/响应拦截
    this.instance.interceptors.request.use(
      this.interceptors?.requestInterceptor,
      this.interceptors?.requestInterceptorCatch
    )
    this.instance.interceptors.response.use(
      this.interceptors?.responseInterceptor,
      this.interceptors?.responseInterceptorCatch
    )

    // 添加所有实例都有的 => 请求拦截器/响应拦截
    this.instance.interceptors.request.use(
      (config) => {
        if (this.showLoading) {
          this.loading = ElLoading.service({
            text: "加载中。。。",
            lock: true,
            background: "rgba(0,0,0,.3)"
          })
        }
        return config
      },
      (err) => {
        return err
      }
    )
    this.instance.interceptors.response.use(
      (res) => {
        this.loading?.close()
        const data = res.data
        return data
      },
      (err) => {
        this.loading?.close()
        return err
      }
    )
  }

  request(config) {
    return new Promise((resolve, reject) => {
      // 单个请求配置的config 处理
      if (config.interceptors?.requestInterceptor) {
        config = config.interceptors.requestInterceptor(config)
      }
      // 将传入的值复制给实例
      if (config.showLoading === false) {
        this.showLoading = config.showLoading
      }
      // 发送请求
      this.instance
        .request(config)
        .then((res) => {
          // 配置单独请求的响应拦截
          if (config.interceptors?.responseInterceptor) {
            res = config.interceptors?.responseInterceptor(res)
          }
          this.showLoading = DEFAULT_LOADING
          if (res.status === 401) {
            alert("token过期")
            return
          } else if (res.status !== 200) {
            ElMessage({
              message: res.message || res.response?.statusText || "请求错误",
              type: "error"
            })
            return
          }
          resolve(res)
        })
        .catch((err) => {
          this.showLoading = DEFAULT_LOADING
          reject(err)
        })
    })
  }

  get(config) {
    return this.request({ ...config, method: "GET" })
  }
  post(config) {
    return this.request({ ...config, method: "POST" })
  }
  patch(config) {
    return this.request({ ...config, method: "PATCH" })
  }
  delete(config) {
    return this.request({ ...config, method: "DELETE" })
  }
}

export default MYRequest
